﻿@*
  PropertyTranslation.cshtml
  Part of the Polyglot package.
*@
@inherits umbraco.MacroEngines.DynamicNodeContext
@using umbraco.MacroEngines;
@{
    int nodeID = PageData[0];
    string property = PageData[1];
    string selectedLanguage = PageData[2];

    DynamicNode page = new DynamicNode(nodeID);

    var value = string.Empty;

    var prop = page.GetPropertyValue(property + "_" + selectedLanguage);
    if (prop != null)
    {
        value = prop;
    }

    if (string.IsNullOrEmpty(value))
    {
        foreach (DynamicNode child in page.GetChildrenAsList)
        {
            if (child.NodeTypeAlias == page.NodeTypeAlias + "_TranslationFolder")
            {
                foreach (DynamicNode translation in child.GetChildrenAsList)
                {
                    prop = translation.GetPropertyValue("language");

                    if (prop != null && prop.ToString().ToLower() == selectedLanguage.ToLower())
                    {
                        prop = translation.GetPropertyValue(property);
                    }
                    else
                    {
                        prop = null;
                    }

                    if (prop != null)
                    {
                        value = prop;
                    }
                }
            }
        }
    }

    if (string.IsNullOrEmpty(value))
    {
        prop = page.GetPropertyValue(property);
        if (prop != null)
        {
            value = prop;
        }
    }

    @Html.Raw(value)
}